package cn.tedu.charging.order.RabbitMQ;


import cn.tedu.charging.order.config.RabbitMqConfiguration;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


@Slf4j
@Component
public class RabbitMQProducer {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    public void sendMessage(String msg) {
        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            if (ack) {
                log.debug("消息发送成功,RabbitMQ成功收到了消息");
            } else {
                log.debug("消息发送失败,RabbitMQ没有收到消息");
                log.debug("失败原因:{}", cause);
                log.debug("如果失败进行重试，重试几次后，还不成功，监控告警");
            }
        });

        //消息持久化
        Message message = new Message(msg.getBytes(), new MessageProperties());
        //消息持久化
        message.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT);



        rabbitTemplate.convertAndSend(RabbitMqConfiguration.EXCHANGE_NAME,
                RabbitMqConfiguration.ROUTING_KEY, message);
    }

}
